import { login, logout, getInfo } from '@/api/login'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { isHttp, isEmpty } from "@/utils/validate"
import defAva from '@/assets/images/profile.jpg'

const useUserStore = defineStore(
  'user',
  {
    state: () => ({
      token: getToken(),
      id: '',
      name: '',
      avatar: '',
      roles: [],
      permissions: [],
      userInfo: {}
    }),
    actions: {
      // 登录
      login(userInfo) {
        // 获取得到登录页面传递过来的数据: 手机号，密码
        const phone = userInfo.phone.trim()
        const password = userInfo.password
        // console.log('login action',phone,password)
        // const code = userInfo.code
        // const uuid = userInfo.uuid
        return new Promise((resolve, reject) => {
          // 调用  src/api/login.js 文件中的 login函数进行登录请求
          login(phone, password).then(res => {
            if(res.code == 500){
              reject(res)
            }
            // res 就是请求返回的结果对象
            // 通过setToken方法将登录得到的token(通行令牌)保存到cookies中
            setToken(res.data.token)
            // console.log(res.data)
            // 同时保存到pinia中
            this.token = res.data.token
            this.userInfo = res.data.user
            resolve()
          }).catch(error => {
            console.log('error')
            reject(error)
          })
        })
      },
      // 获取用户信息
      getInfo() {
        return new Promise((resolve, reject) => {
          getInfo().then(res => {
            const user = res.user
            let avatar = user.avatar || ""
            if (!isHttp(avatar)) {
              avatar = (isEmpty(avatar)) ? defAva : import.meta.env.VITE_APP_BASE_API + avatar
            }
            if (res.roles && res.roles.length > 0) { // 验证返回的roles是否是一个非空数组
              this.roles = res.roles
              // this.permissions = res.permissions
            } else {
              this.roles = ['ROLE_DEFAULT']
            }
            this.id = user.userId
            sessionStorage.setItem('userid', this.id)
            this.name = user.userName
            this.avatar = avatar
            resolve(res)
          }).catch(error => {
            reject(error)
          })
        })
      },
      setPermissions(pers){
        this.permissions = pers
      },
      // 退出系统
      logOut() {
        this.token = ''
        this.roles = []
        this.permissions = []
        sessionStorage.removeItem('userid')
        removeToken()
        location.reload()
        // return new Promise((resolve, reject) => {
        //   logout(this.token).then(() => {

        //     resolve()
        //   }).catch(error => {
        //     reject(error)
        //   })
        // })
      }
    }
  })

export default useUserStore
